<template>
  <div class="ls-add-admin">
    <div class="ls-card">
      <el-page-header @back="$router.go(-1)" :content="identity ? '编辑套餐' : '新增套餐'" />
    </div>

    <div class="ls-card m-t-16 p-20">
      <el-form :rules="rules" ref="form" :model="form" label-width="120px" size="small">
        <!-- 套餐名称 -->
        <el-form-item label="套餐名称" prop="name">
          <el-input class="ls-input" v-model="form.name" placeholder="请输入套餐名称"></el-input>
        </el-form-item>
        <!-- 套餐说明 -->
        <el-form-item label="套餐说明" prop="explain">
          <el-input
            class="ls-input"
            v-model="form.explain"
            placeholder="请输入套餐说明"
            type="textarea"
            rows="10"
          ></el-input>
        </el-form-item>

        <!-- 套餐价格 -->
        <el-form-item label="套餐价格">
          <template v-for="(item, index) in form.set_meal_price">
            <div class="flex m-b-10">
              <el-input v-model="form.set_meal_price[index].time" class="price-input">
                <template slot="append">
                  <el-select class="ls-select" v-model="form.set_meal_price[index].time_type" placeholder="月">
                    <el-option label="月" :value="1"></el-option>
                    <el-option label="年" :value="2"></el-option>
                  </el-select>
                </template>
              </el-input>
              <el-input v-model="form.set_meal_price[index].price" class="price-input m-l-15 m-r-15">
                <template slot="append">元</template>
              </el-input>
              <el-button type="text" size="small" @click="handleSPecDel(index)">删除</el-button>
            </div>
          </template>
          <div class="muted xs m-t-10">
            <el-button type="text" size="small" @click="handleSpecAdd">+添加规格</el-button>
            <span class="m-l-10">最多支持3条</span>
          </div>
        </el-form-item>
        <el-form-item label="排序">
          <el-input class="ls-input" v-model="form.sort" placeholder="请输入"></el-input>
        </el-form-item>
        <!-- 套餐状态 -->
        <el-form-item label="套餐状态" required>
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>

    <!-- 底部保存或取消 -->
    <div class="bg-white ls-fixed-footer">
      <div class="row-center flex" style="height: 100%;">
        <el-button size="small" @click="$router.go(-1)">取消</el-button>
        <el-button size="small" type="primary" @click="onSubmit('form')">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import { apiSetMealDetail, apiSetMealAdd, apiSetMealEdit } from '@/api/shop'
import { debounce } from '@/utils/util'

@Component
export default class SetMealEdit extends Vue {
  /** S Data **/

  identity: number | null = null; // 当前编辑用户的身份ID

  // 添加商城表单数据
  form: any = {
    name: '', // 名称
    explain: '',
    status: 1,
    sort: '',
    set_meal_price: [{
      time: '',
      time_type: 1,
      price: ''
    }]
  };

  // 表单校验
  rules = {
    name: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
    explain: [
      { required: true, message: '请输入套餐说明', trigger: 'blur' }
    ]
  };

  /** E Data **/

  /** S Methods **/
  handleSpecAdd () {
    if (this.form.set_meal_price.length >= 3) return this.$message.error('最多添加3条')
    this.form.set_meal_price.push({
      time: '',
      time_type: 1,
      price: ''
    })
  }

  handleSPecDel (index: number) {
    if (this.form.set_meal_price.length <= 1) return this.$message.error('最后一条不允许删除')
    this.form.set_meal_price.splice(index, 1)
  }

  // 点击表单提交
  onSubmit (formName: string) {
    // 验证表单格式是否正确
    const refs = this.$refs[formName] as HTMLFormElement
    refs.validate((valid: boolean): any => {
      if (!valid) return

      if (!this.identity) {
        this.handleSetMealAdd()
      } else {
        this.handleSetMealEdit()
      }
    })
  }

  // 添加商城
  async handleSetMealAdd (): Promise<void> {
    await apiSetMealAdd({ ...this.form })
    setTimeout(() => this.$router.go(-1), 500)
  }

  // 编辑商城
  async handleSetMealEdit (): Promise<void> {
    await apiSetMealEdit({ ...this.form, id: this.identity })
    setTimeout(() => this.$router.go(-1), 500)
  }

  // 获取详情
  async getSetMealDetailFunc (): Promise<void> {
    const res: any = await apiSetMealDetail({
      id: this.identity as number
    })
    Object.keys(res).map((key) => {
      this.$set(this.form, key, res[key])
    })
  }

  /** E Methods **/

  /** S Life Cycle **/
  created () {
    const query: any = this.$route.query

    // 编辑模式：初始化数据
    this.identity = +query.id
    if (+query.id) {
      this.getSetMealDetailFunc()
    }

    this.onSubmit = debounce(this.onSubmit, 2000)
  }
  /** E Life Cycle **/
}
</script>

<style lang="scss" scoped>
.ls-add-admin {
  padding-bottom: 80px;
}
.ls-input {
  width: 380px !important;
}
.ls-select {
  width: 70px;
}
.price-input {
  width: 150px !important;
}
</style>
